Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Networking → Socket Programming

Networking

Socket Programming

Socket programming in Java allows applications to communicate over a network. It's based on the client-server model, where a client initiates a connection to a server, and they exchange data. Java's `java.net` package provides the necessary classes. Let's explore this with detailed examples.

1. The Basics: `Socket` and `ServerSocket`

`ServerSocket`: Represents the server's endpoint. It listens for incoming connections on a specified port. `Socket`: Represents a connection between the client and the server. A client creates a `Socket` to connect to the server, while the server accepts incoming connections using its `ServerSocket` and receives a `Socket` object representing that connection.

2. Example: A Simple Echo Server and Client

This example demonstrates a basic echo server that sends back whatever it receives from the client. Server (EchoServer.java):
Basic echo server example import java.io.*; import java.net.*; public class EchoServer { public static void main(String[] args) { try { int port = 8080; // Choose a port number ServerSocket serverSocket = new ServerSocket(port); System.out.println("Echo server listening on port " + port); while (true) { Socket clientSocket = serverSocket.accept(); // Accept incoming connection System.out.println("Accepted connection from " + clientSocket.getInetAddress()); // Use streams for communication BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("Received: " + inputLine); out.println("Echo: " + inputLine); // Echo back the message if (inputLine.equals("bye")) break; // Exit condition } in.close(); out.close(); clientSocket.close(); } } catch (IOException e) { e.printStackTrace(); } } }
Client (EchoClient.java):
Basic echo client example import java.io.*; import java.net.*; public class EchoClient { public static void main(String[] args) { try { String serverAddress = "localhost"; // Or the server's IP address int port = 8080; Socket socket = new Socket(serverAddress, port); System.out.println("Connected to server"); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); String response = in.readLine(); System.out.println("Server: " + response); if (userInput.equals("bye")) break; } in.close(); out.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
3. Explanation: Server: The server creates a `ServerSocket` on a specific port (8080 in this case). It then enters a loop, waiting for incoming connections using `serverSocket.accept()`. For each connection, it creates input and output streams (`BufferedReader` and `PrintWriter`) to communicate with the client. It reads lines from the input stream, echoes them back to the client through the output stream, and closes the connection when the client sends "bye". Client: The client creates a `Socket` to connect to the server's address and port. It then establishes input and output streams similar to the server. It reads user input from the console, sends it to the server, receives the server's response, and prints it to the console.

4. Handling Multiple Clients (Multithreading):

For a server to handle multiple clients concurrently, you need multithreading. Each client connection should be handled in a separate thread. Here's a modified server example:
muliple client example import java.io.*; import java.net.*; public class MultithreadedEchoServer { public static void main(String[] args) { // ... (ServerSocket creation remains the same) ... while (true) { Socket clientSocket = serverSocket.accept(); new Thread(new ClientHandler(clientSocket)).start(); // Handle each client in a separate thread } } static class ClientHandler implements Runnable { private Socket clientSocket; public ClientHandler(Socket socket) { this.clientSocket = socket; } @Override public void run() { // ... (same client handling logic as in the single-threaded server) ... } } }
This uses a nested `ClientHandler` class that implements `Runnable` to handle each client's connection in a separate thread. `Thread.start()` creates and starts a new thread for each client.

5. Error Handling and Resource Management:

The examples include basic error handling (`try-catch` blocks). In production applications, more robust error handling and resource management (using `finally` blocks to ensure resources are closed even if exceptions occur) are crucial. Remember to compile and run both the server and the client separately. The server needs to be running before the client attempts to connect. This detailed explanation and the provided examples give a solid foundation for understanding socket programming in Java. You can expand upon these examples to build more complex network applications. Remember to choose appropriate ports (ports below 1024 usually require administrator privileges).

Tutorials